class SearchController < ApplicationController
  layout "index"
  
  def index
    @search_text = params[:search] ? params[:search].strip : ""
    if @search_text == ""
      @results = Array.new
      return
    end
    @count_links = [20,50,100,250,500]
    @limit = params[:limit] ? params[:limit].to_i : 20
    text = "%"+@search_text+"%"
    ecases = Ecase.find(:all,:select =>"ecases.id ,ecases.title,countries.name",:conditions =>[ "title LIKE ? OR description LIKE ? OR tags  LIKE ? ",text,text,text], :order => "countries.name ASC, title ASC" ,:joins => "INNER JOIN countries ON countries.id = country_id" )
    events = Event.find(:all,:select =>"events.id as id,events.ecase_id,ecases.title as title,events.title as event_title,countries.name", :conditions =>[ "events.title LIKE ? OR events.description LIKE ? OR events.tags  LIKE ? ",text,text,text] ,:joins => "INNER JOIN ecases ON ecases.id = events.ecase_id INNER JOIN countries ON countries.id = country_id", :order => "ecases.id ASC , events.title  ASC" )
    no_ecsize = (ecases.size == 0)
    no_evsize = (events.size == 0)
    if no_ecsize && no_evsize
     @results = Array.new
    elsif no_evsize
     @results = ecases
     @res_size = @results.size
    else
      extra_ecases_pre = (events.reject{|i|  !(ecases.detect{|j| j.id == i.ecase_id}).nil? }).sort_by {|pree| pree.ecase_id}
      extra_ecases = Array.new
      extra_ecases_pre.each_with_index { |e, index| 
       if index==0
        extra_ecases.push(e)  
       else 
        if(extra_ecases_pre[index-1].ecase_id != e.ecase_id)
          extra_ecases.push(e) 
        end
       end
      } 
      list_of_all_ecases = ecases.concat(extra_ecases)
      @res_size = list_of_all_ecases.size
      list_of_all_ecases.each do |e|
          e[:events] = events.reject{|i| i.ecase_id != (e[:ecase_id] ? e[:ecase_id] : e.id )}
          @res_size += e[:events].size
      end
      @results = list_of_all_ecases.sort_by {|o| o.name}
    end
  end
  
end
